from rest_framework import status, permissions
from django.contrib import auth
from rest_framework.response import Response
from random import randint
from rest_framework.decorators import permission_classes
from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
from operations.serializers  import WeiboUserLoginSerializer
from users.models import UserInfo,WeiboUser
from rest_framework.authtoken.models import Token

@permission_classes([permissions.AllowAny])
class WeiboUserLogin(GenericViewSet, mixins.CreateModelMixin):
    serializer_class = WeiboUserLoginSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        weibo_id = serializer.validated_data.get('weibo_id')
        username = serializer.validated_data.get('username')

        headers = self.get_success_headers(serializer.data)

        weibo_user = WeiboUser.objects.filter(weibo_id=weibo_id).first()
        if weibo_user:
            auth.login(request=request, user=weibo_user.user)
            old_token = Token.objects.filter(user=weibo_user.user)
            old_token.delete()
            token = Token.objects.create(user=weibo_user.user)
            data = {'result':"user exist login success"}
            data["success"] = True
            data["code"] = 201
            data["token"] = token.key
            return Response(data=data, status=status.HTTP_201_CREATED, headers=headers)

        while UserInfo.objects.filter(username=username):
            username += str(randint(0, 9))

        user = UserInfo.objects.create(username=username)
        WeiboUser.objects.create(weibo_id=weibo_id, user=user)
        auth.login(request=request, user=user)
        token = Token.objects.create(user=user)

        data = {'result':"user create success"}
        data["success"] = True
        data["code"] = 201
        data["token"] = token.key
        return Response(data=data, status=status.HTTP_201_CREATED, headers=headers)
